<template>
  <div class="profile-container gradient-bg">
    <header class="header glass">
      <el-button @click="$router.back()" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2>个人资料</h2>
      <div style="width: 100px"></div>
    </header>

    <div class="profile-content">
      <div class="profile-card glass">
        <div class="avatar-section">
          <div class="current-avatar">{{ getAvatarEmoji(user.avatar) }}</div>
          <el-button type="primary" size="small" @click="showAvatarDialog = true">更换头像</el-button>
        </div>

        <el-form :model="profileForm" label-width="100px" class="profile-form">
          <el-form-item label="用户名">
            <el-input v-model="profileForm.username" disabled />
          </el-form-item>
          
          <el-form-item label="学校">
            <el-input v-model="profileForm.school" placeholder="请输入学校名称" />
          </el-form-item>
          
          <el-form-item label="年级">
            <el-select v-model="profileForm.grade" placeholder="选择年级">
              <el-option label="三年级上学期" value="三上" />
              <el-option label="三年级下学期" value="三下" />
              <el-option label="四年级上学期" value="四上" />
              <el-option label="四年级下学期" value="四下" />
              <el-option label="五年级上学期" value="五上" />
              <el-option label="五年级下学期" value="五下" />
              <el-option label="六年级上学期" value="六上" />
              <el-option label="六年级下学期" value="六下" />
            </el-select>
          </el-form-item>

          <el-form-item label="注册时间">
            <el-input :value="formatDate(user.created_at)" disabled />
          </el-form-item>

          <el-form-item label="最后登录">
            <el-input :value="formatDate(user.last_login)" disabled />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="saveProfile" :loading="loading">保存修改</el-button>
            <el-button @click="showPasswordDialog = true">修改密码</el-button>
          </el-form-item>
        </el-form>

        <div class="stats-section">
          <h3>📊 学习统计</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="stat-icon">⭐</div>
              <div class="stat-info">
                <div class="stat-value">{{ user.stars || 0 }}</div>
                <div class="stat-label">总星星数</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">🔥</div>
              <div class="stat-info">
                <div class="stat-value">{{ user.continuous_days || 0 }}</div>
                <div class="stat-label">连续天数</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">✅</div>
              <div class="stat-info">
                <div class="stat-value">{{ user.total_correct || 0 }}</div>
                <div class="stat-label">正确数</div>
              </div>
            </div>
            <div class="stat-item">
              <div class="stat-icon">❌</div>
              <div class="stat-info">
                <div class="stat-value">{{ user.total_wrong || 0 }}</div>
                <div class="stat-label">错误数</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 更换头像对话框 -->
    <el-dialog v-model="showAvatarDialog" title="选择头像" width="500px">
      <div class="avatar-grid">
        <div 
          v-for="(emoji, index) in avatarEmojis" 
          :key="index"
          class="avatar-option"
          :class="{ selected: selectedAvatar === `avatar${index + 1}` }"
          @click="selectedAvatar = `avatar${index + 1}`"
        >
          {{ emoji }}
        </div>
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="changeAvatar">确定</el-button>
      </template>
    </el-dialog>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="当前密码">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()
const user = computed(() => userStore.user || {})

const loading = ref(false)
const showAvatarDialog = ref(false)
const showPasswordDialog = ref(false)
const selectedAvatar = ref('')

const avatarEmojis = ['🐭', '🐮', '🐯', '🐰', '🐲', '🐍', '🐴', '🐏', '🐵', '🐔', '🐶', '🐷']

const profileForm = reactive({
  username: '',
  school: '',
  grade: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const getAvatarEmoji = (avatar?: string) => {
  if (!avatar) return '😊'
  const match = avatar.match(/\d+/)
  if (match) {
    const index = parseInt(match[0]) - 1
    return avatarEmojis[index] || '😊'
  }
  return '😊'
}

const formatDate = (date: any) => {
  if (!date) return '未知'
  return new Date(date).toLocaleString('zh-CN')
}

const saveProfile = async () => {
  try {
    loading.value = true
    const res = await request.put('/auth/profile', {
      school: profileForm.school,
      grade: profileForm.grade
    })
    
    if (res.success) {
      ElMessage.success('资料已更新')
      // 更新本地用户信息
      userStore.user = { ...userStore.user, ...profileForm }
    }
  } catch (error: any) {
    console.error('更新资料失败:', error)
    ElMessage.error(error.response?.data?.message || '更新资料失败')
  } finally {
    loading.value = false
  }
}

const changeAvatar = async () => {
  try {
    const res = await request.put('/auth/profile', {
      avatar: selectedAvatar.value
    })
    
    if (res.success) {
      ElMessage.success('头像已更换')
      userStore.user = { ...userStore.user, avatar: selectedAvatar.value }
      showAvatarDialog.value = false
    }
  } catch (error: any) {
    console.error('更换头像失败:', error)
    ElMessage.error(error.response?.data?.message || '更换头像失败')
  }
}

const changePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次密码输入不一致')
    return
  }
  
  if (passwordForm.newPassword.length < 6) {
    ElMessage.error('密码长度至少6位')
    return
  }
  
  try {
    const res = await request.put('/auth/password', {
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (res.success) {
      ElMessage.success('密码已修改')
      showPasswordDialog.value = false
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }
  } catch (error: any) {
    console.error('修改密码失败:', error)
    ElMessage.error(error.response?.data?.message || '修改密码失败')
  }
}

onMounted(() => {
  profileForm.username = user.value.username || ''
  profileForm.school = user.value.school || ''
  profileForm.grade = user.value.grade || ''
  selectedAvatar.value = user.value.avatar || 'avatar1'
})
</script>

<style scoped lang="scss">
.profile-container {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  margin-bottom: 30px;
  
  h2 {
    color: white;
    margin: 0;
    font-size: 1.5rem;
  }
}

.profile-content {
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  padding: 40px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 40px;
  
  .current-avatar {
    font-size: 6rem;
    margin-bottom: 20px;
  }
}

.profile-form {
  :deep(.el-input__inner),
  :deep(.el-select) {
    background: rgba(255, 255, 255, 0.9);
    border-color: rgba(255, 255, 255, 0.3);
    color: #333;
  }
  
  :deep(.el-input.is-disabled .el-input__inner) {
    background: rgba(255, 255, 255, 0.5);
    color: #666;
  }
  
  :deep(.el-form-item__label) {
    color: rgba(255, 255, 255, 0.9);
  }
}

.stats-section {
  margin-top: 40px;
  padding-top: 30px;
  border-top: 2px solid rgba(255, 255, 255, 0.1);
  
  h3 {
    color: white;
    margin-bottom: 20px;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  
  .stat-icon {
    font-size: 2.5rem;
  }
  
  .stat-info {
    .stat-value {
      font-size: 1.8rem;
      font-weight: bold;
      color: white;
    }
    
    .stat-label {
      font-size: 0.9rem;
      color: rgba(255, 255, 255, 0.7);
    }
  }
}

.avatar-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 15px;
  padding: 20px 0;
}

.avatar-option {
  font-size: 3rem;
  text-align: center;
  padding: 15px;
  border-radius: 10px;
  border: 3px solid transparent;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: rgba(102, 126, 234, 0.1);
    transform: scale(1.1);
  }
  
  &.selected {
    border-color: #667eea;
    background: rgba(102, 126, 234, 0.2);
  }
}
</style>

